﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Google.Ads.GoogleAds;
using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Lib;
using Google.Api;
using Google.Apis.Auth.OAuth2;
using Google.Type;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace Coldairarrow.Business.Interface
{
    public class Ads_DataReprotInterfaceBusiness : AdsInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption SrarchOption { get; set; }
        //配置参数
        public List<Base_ConfigParameter> ConfigParam { get; set; }
        public Ads_DataReprotInterfaceBusiness()
        {
            this.InterfaceName = "谷歌数据报表";
            //索引字段
            this.MapFields = GetMapField("S");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            SrarchOption = this.interfaceOption.Where(x => x.OperateType == "Srarch").First();

            //获取此接口的所有API参数
            ConfigParam = SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='GoogleAds' ");




            //获取配置参数

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ADS_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, ADS_NoQueryEventArgs ADS_NoQueryEventArgs)
        {
            //API请求是否成功
            ADS_NoQueryEventArgs.Success = ADS_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, ADS_QueryEventArgs queryEventArgs)
        {
            try
            {
                queryEventArgs.customerId = ConfigParam.Where(x => x.Name == "CustomerId").First().Value;
                // 初始化 Google Ads 客户端配置
                queryEventArgs.config = new GoogleAdsConfig
                {
                    DeveloperToken = ConfigParam.Where(x => x.Name == "DeveloperToken").First().Value,
                    OAuth2ClientId = ConfigParam.Where(x => x.Name == "OAuth2ClientId").First().Value,
                    OAuth2ClientSecret = ConfigParam.Where(x => x.Name == "OAuth2ClientSecret").First().Value,
                    OAuth2RefreshToken = ConfigParam.Where(x => x.Name == "OAuth2RefreshToken").First().Value
                };
                // 创建 Google Ads 客户端
                queryEventArgs.client = new GoogleAdsClient(queryEventArgs.config);
                // 获取 Google Ads 服务
                queryEventArgs.service = queryEventArgs.client.GetService(Services.V19.GoogleAdsService);
                //获取多少天的数据
                queryEventArgs.Page.Total = ConfigParam.Where(x => x.Name == "Days").First().Value.ToInt();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }


        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, ADS_QueryEventArgs queryEventArgs)
        {
            try
            {
                string startDate = System.DateTime.Now.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd");
                string endDate = System.DateTime.Now.ToString("yyyy-MM-dd");
                queryEventArgs.reqData=queryEventArgs.reqData.Replace("@startDate", startDate);
                queryEventArgs.reqData=queryEventArgs.reqData.Replace("@endDate", endDate);

            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, ADS_QueryEventArgs queryEventArgs)
        {

            try
            {
                if (queryEventArgs.Page.Count == queryEventArgs.Page.GetCount)
                {
                    queryEventArgs.Page.Complete = true;
                    queryEventArgs.Success = true;
                }
                else
                {
                    queryEventArgs.Success = false;
                }
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            List<DataReprot> QQ = await this.QueryAsync<DataReprot>(this.SrarchOption, SqlDb);
        }


        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }




    }

}
